// components/dd-acti/dd-prd-img/index.js
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
var { getFileExtension } = require('../../../pages/utils/file');
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    formData: { type: Object, value: {}, observer: 'updateFormData', },
  },

  /**
   * 组件的初始数据
   */
  data: {
    CustomBar: getApp().globalData.CustomBar,
    form: {
      // 活动图片
      fileList: [],
      // 活动图片文件序号列表
      actiFileIdList: '',
      // 商品列表
      actiPrdList: [
        {
          // 商品折叠面板标题
          title: "商品1",
          // 商品折叠面板名称
          name: "1",
          // 临时-商品图片列表
          fileList: [],
          // 商品详情
          prdInfo: {
            // 商品序号
            prdId: 0,
            // 商品名称
            prdName: '',
            // 活动方式-多层级活动开关
            currActiModeSwitch: false,
            // 活动方式列表
            actiModeList: [],
            // 活动方式列表展示
            actiModeList_label: '',
            // 活动时间列表展示
            actiTimeList_label: '',
            // 商品简介
            prdContent: '',
            // 商品价格
            prdPrice: '',
            // 商品数量
            prdVol: '',
            // 商品工期
            prdDays: '',
            // 商品点数
            prdPointCount: '',
            // 商品文件序号列表
            prdFileIdList: '',
            // 正式-商品图片列表
            fileList: [],
          },
        }
      ],
    },
    // 发布活动loading状态
    submitLoading: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    updateFormData(newValue) {
      if (JSON.stringify(newValue) != "{}") {
        this.setData({ form: newValue });
      }
    },
    // 文件选择后
    actiAfterRead(event) {
      const fileList = event.detail.file;
      // 组装文件前缀
      let index = 0;
      for (const file of fileList) {
        const currDate = new Date().toLocaleDateString().replaceAll('/', '-');
        const userId = getApp().globalData.userInfo.userId;
        const filePath = 'acti_picture/' + currDate + '/' + userId + '/';
        const fileName = '活动图片' + '-' + index + '-' + new Date().getTime() + '.' + getFileExtension(file.url);
        file.fileName = filePath + fileName;
        index++;
      }
      // 调用文件上传接口
      const uploadTasks = fileList.map((file) => getApp().uploadFilePromise(file.fileName, file));
      Promise.all(uploadTasks)
        .then(data => {
          Toast('上传成功');
          const newFileList = data.map(item => ({ url: item.fileID }));
          for (const newFile of newFileList) {
            this.data.form.fileList.push(newFile);
          }
          this.setData({ 'form.fileList': this.data.form.fileList });
          this.onConfirmUpload();
        })
        .catch(e => {
          Toast('上传失败');
          console.log(e);
        });
    },
    // 删除图片
    actiDeleteFile(event) {
      this.data.form.fileList.splice(event.detail.index, 1);
      this.setData({ 'form.fileList': this.data.form.fileList });
      this.onConfirmUpload();
    },
    // 文件选择后
    afterRead(event) {
      const prdIndex = event.currentTarget.dataset.operation;
      const fileList = event.detail.file;
      // 组装文件前缀
      let index = 0;
      for (const file of fileList) {
        const currDate = new Date().toLocaleDateString().replaceAll('/', '-');
        const userId = getApp().globalData.userInfo.userId;
        const prdTitle = this.data.form.actiPrdList[prdIndex].title;
        const filePath = 'acti_picture/' + currDate + '/' + userId + '/';
        const fileName = prdTitle + '-' + index + '-' + new Date().getTime() + '.' + getFileExtension(file.url);
        file.fileName = filePath + fileName;
        index++;
      }
      // 调用文件上传接口
      const uploadTasks = fileList.map((file) => getApp().uploadFilePromise(file.fileName, file));
      Promise.all(uploadTasks)
        .then(data => {
          Toast('上传成功');
          const newFileList = data.map(item => ({ url: item.fileID }));
          for (const newFile of newFileList) {
            this.data.form.actiPrdList[prdIndex].fileList.push(newFile);
          }
          this.setData({ 'form.actiPrdList': this.data.form.actiPrdList });
          this.onConfirmUpload();
        })
        .catch(e => {
          Toast('上传失败');
          console.log(e);
        });
    },
    // 删除图片
    deleteFile(event) {
      const prdIndex = event.currentTarget.dataset.operation;
      this.data.form.actiPrdList[prdIndex].fileList.splice(event.detail.index, 1);
      this.setData({ 'form.actiPrdList': this.data.form.actiPrdList });
      this.onConfirmUpload();
    },
    // 上传图片-确定
    onConfirmUpload() {
      if (this.data.form.actiPrdList) {
        for (const actiPrd of this.data.form.actiPrdList) {
          const fileIdArr = actiPrd.fileList.map(e => (e.url));
          actiPrd.prdInfo.prdFileIdList = fileIdArr.join(',');
          actiPrd.prdInfo.fileList = JSON.parse(JSON.stringify(actiPrd.fileList));
        }
      }
      if (this.data.form.fileList) {
        const fileIdArr = this.data.form.fileList.map(e => (e.url));
        this.data.form.actiFileIdList = fileIdArr.join(',');
      }
      this.setData({ 'form.actiPrdList': this.data.form.actiPrdList, 'form.actiFileIdList': this.data.form.actiFileIdList });
      this.triggerEvent('saveData', this.data.form);
    },
    // 上一步
    onClickToLastStep() {
      this.triggerEvent('lastStep', this.data.form);
    },
    // 下一步
    onClickToNextStep() {
      this.triggerEvent('nextStep', this.data.form);
    },
    // 校验参数
    checkParam() {
      const formData = this.data.form;
      if (formData.actiTitle == '') {
        Toast('请输入活动标题！');
        return false;
      }
      if (formData.actiEndTime < formData.actiBegnTime) {
        Toast('结束时间必须大于等于开始时间！');
        return false;
      }
      for (const actiPrd of formData.actiPrdList) {
        if (actiPrd.prdInfo.prdName == '') {
          Toast('请输入' + actiPrd.title + '的商品名称！');
          return false;
        } else if (actiPrd.prdInfo.actiModeList == null || actiPrd.prdInfo.actiModeList.length == 0) {
          Toast('请选择' + actiPrd.title + '的活动方式！');
          return false;
        } else if (actiPrd.prdInfo.prdPrice == '') {
          Toast('请输入' + actiPrd.title + '的商品价格！');
          return false;
        } else if (isNaN(Number(actiPrd.prdInfo.prdPrice))) {
          Toast(actiPrd.title + '的商品价格格式不正确！');
          return false;
        } else if (actiPrd.prdInfo.prdVol == '') {
          Toast('请输入' + actiPrd.title + '的商品数量！');
          return false;
        } else if (isNaN(Number(actiPrd.prdInfo.prdVol))) {
          Toast(actiPrd.title + '的商品数量格式不正确！');
          return false;
        } else if (!actiPrd.prdInfo.prdFileIdList || actiPrd.prdInfo.prdFileIdList.length == 0) {
          Toast('请上传' + actiPrd.title + '的图片！');
          return false;
        }
      }
      return true;
    },
    // 转换参数
    transParam() {
      const formData = this.data.form;
      let actiPrdInfoDTOList = [];
      for (const actiPrd of formData.actiPrdList) {
        let actiModeMaxLevel = 1;
        for (const actiMode of actiPrd.prdInfo.actiModeList) {
          if (actiModeMaxLevel < actiMode.actiModeLevel) {
            actiModeMaxLevel = actiMode.actiModeLevel;
          }
        }
        actiPrdInfoDTOList.push({
          prdId: actiPrd.prdInfo.prdId,
          prdName: actiPrd.prdInfo.prdName,
          prdContent: actiPrd.prdInfo.prdContent,
          prdPrice: actiPrd.prdInfo.prdPrice,
          prdVol: actiPrd.prdInfo.prdVol,
          prdDays: actiPrd.prdInfo.prdDays,
          prdPointCount: actiPrd.prdInfo.prdPointCount,
          prdFileIdList: actiPrd.prdInfo.prdFileIdList,
          actiModeMaxLevel: actiModeMaxLevel,
          actiPrdModeInfoDTOList: actiPrd.prdInfo.actiModeList || [],
          actiPrdGoodsTypeInfoAddDTOList: actiPrd.prdInfo.actiGoodsTypeList || [],
        });
      }
      return {
        actiId: formData.actiId,
        actiTitle: formData.actiTitle,
        actiDate: formData.actiDate,
        actiBegnTime: formData.actiBegnTime,
        actiEndTime: formData.actiEndTime,
        actiMemo: formData.actiMemo,
        actiFileIdList: formData.actiFileIdList,
        storeId: getApp().globalData.userInfo.storeId,
        storeName: getApp().globalData.userInfo.storeName,
        actiPrdInfoDTOList: actiPrdInfoDTOList,
      }
    },
    // 发布活动提交
    onClickToSubmit() {
      if (this.data.submitLoading) {
        return;
      }
      if (!this.checkParam()) {
        this.setData({ submitLoading: false });
        return;
      }
      wx.requestSubscribeMessage({
        tmplIds: ['pATN40-Jqv75gFva6r7sBKwkaXgHA3qBZynpW8C1Qtg'],
        success: (res) => {
          this.setData({ submitLoading: true });
          const param = this.transParam();
          let url = "/acti/add";
          if (this.data.form.actiId) {
            url = "/acti/upd";
          }
          getApp().callContainer(url, param, (res) => {
            if (res.data.code == 0) {
              this.setData({ submitLoading: false });
              Notify({ type: 'success', message: '发布成功！', top: this.data.CustomBar });
              this.onClickToNextStep();
            } else {
              this.setData({ submitLoading: false });
              Notify({ type: 'danger', message: '发布失败！', top: this.data.CustomBar });
            }
          }, (res) => {
            this.setData({ submitLoading: false });
          })
        },
      });
    },
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      if (JSON.stringify(this.properties.formData) != "{}") {
        this.setData({ form: this.properties.formData });
      }
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
})